<template>
  <div class="qr-code-settings-container">
    <el-row :gutter="20">
      <el-col :span="10">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>当前群聊二维码</span>
            </div>
          </template>
          <div class="qr-code-display" v-loading="loadingCurrent">
            <template v-if="currentQrCode">
              <div class="qr-info">
                <el-image
                  :src="currentQrCode.qrCodeUrl"
                  fit="contain"
                  style="width: 250px; height: 250px; border: 1px solid #eee"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
                <div class="qr-details">
                  <p><strong>上传时间：</strong>{{ formatDateTime(currentQrCode.uploadTime) }}</p>
                  <p v-if="currentQrCode.expiryTime">
                    <strong>过期时间：</strong>{{ formatDateTime(currentQrCode.expiryTime) }}
                  </p>
                  <p>
                    <strong>状态：</strong
                    >{{ currentQrCode.status === 'Active' ? '生效中' : '已失效' }}
                  </p>
                  <p><strong>上传者：</strong>{{ currentQrCode.creatorName }}</p>
                </div>
              </div>
            </template>
            <el-empty v-else description="暂无可用的群聊二维码" :image-size="100"></el-empty>
          </div>
        </el-card>
      </el-col>
      <el-col :span="14">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>上传新二维码</span>
            </div>
          </template>
          <el-form :model="uploadForm" label-width="100px" label-position="top">
            <el-form-item label="二维码图片" required>
              <el-upload
                class="qr-uploader"
                :auto-upload="false"
                :show-file-list="true"
                :limit="1"
                :on-change="handleFileChange"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                accept="image/png, image/jpeg, image/gif"
              >
                <el-button type="primary" :icon="Upload">选择图片</el-button>
                <template #tip>
                  <div class="el-upload__tip">请上传 JPG/PNG/GIF 格式的图片，且大小不超过 2MB</div>
                </template>
              </el-upload>
            </el-form-item>

            <el-form-item label="过期时间">
              <el-date-picker
                v-model="uploadForm.expiryTime"
                type="datetime"
                placeholder="选择过期时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
                :disabledDate="disabledDate"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="状态">
              <div style="width: 300px">
                <el-select
                  v-model="uploadForm.status"
                  placeholder="选择状态"
                  class="status-select"
                  style="width: 100%"
                >
                  <el-option label="生效" value="Active" class="status-option" />
                  <el-option label="失效" value="Inactive" class="status-option" />
                </el-select>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="success"
                @click="submitUpload"
                :disabled="!uploadForm.qrCodeImage"
                :loading="uploading"
              >
                上传二维码
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 历史二维码列表 -->
    <el-card class="box-card history-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>二维码管理</span>
          <el-button type="primary" size="small" @click="fetchQrCodeList">刷新</el-button>
        </div>
      </template>

      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="filter-form">
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="全部状态" clearable>
              <el-option label="生效" value="Active" />
              <el-option label="失效" value="Inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchQrCodeList">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="qrCodeList" border style="width: 100%" v-loading="loadingList">
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="qrCodeUrl" label="二维码" width="120">
          <template #default="scope">
            <el-image
              :src="scope.row.qrCodeUrl"
              :preview-src-list="[scope.row.qrCodeUrl]"
              fit="cover"
              style="width: 50px; height: 50px"
            >
              <template #error>
                <div class="image-slot-small">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.uploadTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="expiryTime" label="过期时间" width="180">
          <template #default="scope">
            {{ scope.row.expiryTime ? formatDateTime(scope.row.expiryTime) : '永久有效' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'Active' ? 'success' : 'info'">
              {{ scope.row.status === 'Active' ? '生效中' : '已失效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creatorName" label="上传者" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleUpdate(scope.row)"
              :disabled="updating"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              :disabled="updating"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > 0"
        :current-page="queryParams.current"
        :page-size="queryParams.size"
        :total="Number(total)"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>

    <!-- 更新二维码对话框 -->
    <el-dialog v-model="updateDialogVisible" title="更新群聊二维码" width="500px">
      <el-form :model="updateForm" label-width="100px">
        <el-form-item label="二维码图片">
          <el-upload
            class="update-uploader"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            :on-change="handleUpdateFileChange"
            :on-exceed="handleExceed"
            :on-remove="handleUpdateRemove"
            accept="image/png, image/jpeg, image/gif"
          >
            <el-button type="primary" :icon="Upload">选择新图片</el-button>
            <template #tip>
              <div class="el-upload__tip">可选，不更新图片则保持原图</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="过期时间">
          <el-date-picker
            v-model="updateForm.expiryTime"
            type="datetime"
            placeholder="选择过期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
            :disabledDate="disabledDate"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="状态">
          <div style="width: 300px">
            <el-select
              v-model="updateForm.status"
              placeholder="选择状态"
              class="status-select"
              style="width: 100%"
            >
              <el-option label="生效" value="Active" class="status-option" />
              <el-option label="失效" value="Inactive" class="status-option" />
            </el-select>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpdate" :loading="updating">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile } from 'element-plus'
import { Picture, Upload } from '@element-plus/icons-vue'
import {
  uploadQrCode,
  updateQrCode,
  deleteQrCode,
  getQrCodeList,
  getLatestQrCode,
  type QrCode,
  type QrCodeListQuery,
} from '@/api/system'
import dayjs from 'dayjs'

// 当前二维码数据
const currentQrCode = ref<QrCode | null>(null)
const loadingCurrent = ref(false)

// 上传表单数据
const uploadForm = reactive({
  qrCodeImage: null as File | null,
  expiryTime: '',
  status: 'Active',
})
const uploading = ref(false)

// 二维码列表数据
const qrCodeList = ref<QrCode[]>([])
const loadingList = ref(false)
const total = ref(0)
const queryParams = reactive<QrCodeListQuery>({
  current: 1,
  size: 10,
  status: undefined,
})

// 更新表单数据
const updateDialogVisible = ref(false)
const updateForm = reactive({
  qrCodeId: 0,
  qrCodeImage: null as File | null,
  expiryTime: '',
  status: 'Active',
})
const updating = ref(false)

// 获取最新有效的二维码
const fetchLatestQrCode = async () => {
  loadingCurrent.value = true
  try {
    const res = await getLatestQrCode()
    if (res.code === 200 && res.data) {
      currentQrCode.value = res.data
    } else if (res.code === 404) {
      // 没有找到有效的二维码
      currentQrCode.value = null
    }
  } catch (error) {
    console.error('获取最新二维码失败:', error)
    // ElMessage.error('获取最新二维码失败')
  } finally {
    loadingCurrent.value = false
  }
}

// 获取二维码列表
const fetchQrCodeList = async () => {
  loadingList.value = true
  try {
    const res = await getQrCodeList(queryParams)
    if (res.code === 200 && res.data) {
      qrCodeList.value = res.data.records
      total.value = res.data.total
    } else {
      qrCodeList.value = []
      total.value = 0
      ElMessage.warning(res.message || '获取二维码列表失败')
    }
  } catch (error) {
    console.error('获取二维码列表失败:', error)
    ElMessage.error('获取二维码列表失败')
    qrCodeList.value = []
    total.value = 0
  } finally {
    loadingList.value = false
  }
}

// 处理文件选择变更
const handleFileChange = (file: UploadFile) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.raw?.type || '')
  const isLt2M = file.size ? file.size / 1024 / 1024 < 2 : false

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG/GIF格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }

  uploadForm.qrCodeImage = file.raw as File
  return true
}

// 处理更新时的文件选择变更
const handleUpdateFileChange = (file: UploadFile) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.raw?.type || '')
  const isLt2M = file.size ? file.size / 1024 / 1024 < 2 : false

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG/GIF格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }

  updateForm.qrCodeImage = file.raw as File
  return true
}

// 处理文件数量超出限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传1个文件')
}

// 处理文件移除
const handleRemove = () => {
  uploadForm.qrCodeImage = null
}

// 处理更新时的文件移除
const handleUpdateRemove = () => {
  updateForm.qrCodeImage = null
}

// 提交上传
const submitUpload = async () => {
  if (!uploadForm.qrCodeImage) {
    ElMessage.warning('请选择二维码图片')
    return
  }

  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('qrCodeImage', uploadForm.qrCodeImage)

    if (uploadForm.expiryTime) {
      formData.append('expiryTime', uploadForm.expiryTime)
    }

    formData.append('status', uploadForm.status)

    const res = await uploadQrCode(formData)
    if (res.code === 200 && res.data) {
      ElMessage.success('二维码上传成功')
      // 重置表单
      uploadForm.qrCodeImage = null
      uploadForm.expiryTime = ''
      uploadForm.status = 'Active'
      // 刷新数据
      fetchLatestQrCode()
      fetchQrCodeList()
    } else {
      ElMessage.error(res.message || '上传失败')
    }
  } catch (error) {
    console.error('上传二维码失败:', error)
    ElMessage.error('上传二维码失败')
  } finally {
    uploading.value = false
  }
}

// 处理更新操作
const handleUpdate = (row: QrCode) => {
  updateForm.qrCodeId = row.qrCodeId
  updateForm.qrCodeImage = null
  updateForm.expiryTime = row.expiryTime || ''
  updateForm.status = row.status
  updateDialogVisible.value = true
}

// 提交更新
const submitUpdate = async () => {
  updating.value = true
  try {
    const formData = new FormData()
    formData.append('qrCodeId', updateForm.qrCodeId.toString())

    if (updateForm.qrCodeImage) {
      formData.append('qrCodeImage', updateForm.qrCodeImage)
    }

    if (updateForm.expiryTime) {
      formData.append('expiryTime', updateForm.expiryTime)
    }

    formData.append('status', updateForm.status)

    const res = await updateQrCode(formData)
    if (res.code === 200 && res.data) {
      ElMessage.success('二维码更新成功')
      updateDialogVisible.value = false
      // 刷新数据
      fetchLatestQrCode()
      fetchQrCodeList()
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新二维码失败:', error)
    ElMessage.error('更新二维码失败')
  } finally {
    updating.value = false
  }
}

// 处理删除操作
const handleDelete = async (row: QrCode) => {
  try {
    await ElMessageBox.confirm(`确定要删除该二维码吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    updating.value = true
    const res = await deleteQrCode(row.qrCodeId)
    if (res.code === 200 && res.data) {
      ElMessage.success('删除成功')
      // 刷新数据
      fetchQrCodeList()
      // 如果删除的是当前显示的二维码，也需要刷新当前二维码
      if (currentQrCode.value && currentQrCode.value.qrCodeId === row.qrCodeId) {
        fetchLatestQrCode()
      }
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error: unknown) {
    if (error !== 'cancel') {
      console.error('删除二维码失败:', error)
      ElMessage.error('删除二维码失败')
    }
  } finally {
    updating.value = false
  }
}

// 处理分页变化
const handleCurrentChange = (page: number) => {
  queryParams.current = page
  fetchQrCodeList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.current = 1
  queryParams.status = undefined
  fetchQrCodeList()
}

// 禁用过去的日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now()
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
  fetchLatestQrCode()
  fetchQrCodeList()
})
</script>

<style scoped>
.qr-code-settings-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}
.qr-code-display {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 280px; /* 确保在没有图片时也有一定高度 */
}
.qr-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}
.qr-details {
  margin-top: 15px;
  width: 100%;
  text-align: center;
}
.qr-details p {
  margin: 5px 0;
}
.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
.image-slot-small {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
}
.image-slot .el-icon {
  font-size: 30px;
}
.qr-uploader,
.update-uploader {
  width: 100%;
}
.qr-uploader .el-upload__tip,
.update-uploader .el-upload__tip {
  color: #909399;
  margin-top: 8px;
  line-height: 1.5;
}
.history-card {
  margin-top: 20px;
}
.filter-container {
  margin-bottom: 15px;
}
.status-select {
  width: 200px !important;
}
.status-select :deep(.el-select) {
  width: 200px !important;
}
.status-select :deep(.el-input) {
  width: 200px !important;
}
.status-select :deep(.el-input__wrapper) {
  width: 200px !important;
}
.status-option {
  font-size: 14px;
  padding: 8px 12px;
}
</style>
